package com.bankLogisticsSys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bankLogisticsSys.model.Expressrecord;
import com.bankLogisticsSys.model.Userinfo;
import com.bankLogisticsSys.util.WeixinUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

//发送环节控制器
public class SendController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(SendController.class);
	
	public void index(){
		if(OAUTH2_OPEN){
		String code   = getPara("code");
		if (StrKit.isBlank(code)) {
			renderText("code is Blank!");
		}
		openId = OauthOpenId(code);
		}
		Userinfo user = exservice.getUserinfo(openId);
		int action = SEND_ACTION;
		long trackingID = 0;
		Map<Long, List<Record>> ecMap = new HashMap<Long, List<Record>>();
		Map<Long, List<Expressrecord>> erMap = new HashMap<Long, List<Expressrecord>>();
		List<Record> eiList = new ArrayList<Record>();
		Set<String> trackingIDSet = actionCache.smembers(openId + "List");
		int packageAccount = 0;
		int packageScaned = 0;
		for (String temp : trackingIDSet) {  
			trackingID = Long.parseLong(temp);
			List<Record> ec = exservice.getContentListBCN(trackingID);
			List<Expressrecord> er = exservice.getRecordList(trackingID, user.getEmployeeID(), action);
			Record ei = exservice.getExpressInfo(trackingID);
			ecMap.put(trackingID, ec);
			erMap.put(trackingID, er);
			packageAccount += ec.size();
			packageScaned += er.size();
			eiList.add(ei);
		}
		setAttr("packageAccount", packageAccount);
		setAttr("packageScaned", packageScaned);
		setAttr("expressinfo", eiList);
		setAttr("expressrecord", erMap);
		setAttr("expresscontent", ecMap);
		render("/WEB-INF/content/action/send.html");
	}
	
	//完成发送流程
	public void finish(){
		if(OAUTH2_OPEN){
		String code = getPara("code");
		if (StrKit.isBlank(code)) {
			renderText("code is Blank!");
		}
		openId = OauthOpenId(code);
		}
		int nextNetwork =getNextNetwork(openId);
		System.out.println("nextNetwork" + nextNetwork);
		setAttr("processMsg","数据处理中，处理完成将由微信消息提示");
		render("/WEB-INF/content/action/finish.html");
		Set<String> trackingIDSet = getTrackingIDSet();
		int trackingIDNum = trackingIDSet.size();
		dealWholeProcess(trackingIDSet, SEND_ACTION, false);
		actionCache.del(openId);
		actionCache.del(openId + "List");
		if(trackingIDNum!=0){
			sendProcessMsg(trackingIDNum, SEND_ACTION, nextNetwork,openId);
			logger.info(getLogString(openId, "发送", trackingIDSet));
		}
	}
}
